package com.sh.data.engine.job.admin.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sh.data.engine.job.admin.core.model.XxlJobLogReport;
import org.apache.ibatis.annotations.Mapper;

import java.util.Date;
import java.util.List;

/**
 * job log
 *
 * @author xuxueli 2019-11-22
 */
@Mapper
public interface XxlJobLogReportDao extends BaseMapper<XxlJobLogReport> {

    default int save(XxlJobLogReport xxlJobLogReport) {
        return this.insert(xxlJobLogReport);
    }

    default int update(XxlJobLogReport xxlJobLogReport) {
        LambdaUpdateWrapper<XxlJobLogReport> update = new UpdateWrapper<XxlJobLogReport>().lambda();
        update
            .eq(XxlJobLogReport::getTriggerDay, xxlJobLogReport.getTriggerDay())
            .set(XxlJobLogReport::getRunningCount, xxlJobLogReport.getRunningCount())
            .set(XxlJobLogReport::getSucCount, xxlJobLogReport.getSucCount())
            .set(XxlJobLogReport::getFailCount, xxlJobLogReport.getFailCount());
        return this.update(null, update);
    }

    default List<XxlJobLogReport> queryLogReport(Date triggerDayFrom, Date triggerDayTo) {
        LambdaQueryWrapper<XxlJobLogReport> wrapper = new QueryWrapper<XxlJobLogReport>().lambda();
        wrapper
            .between(XxlJobLogReport::getTriggerDay, triggerDayFrom, triggerDayTo)
            .orderByAsc(XxlJobLogReport::getTriggerDay);
        return this.selectList(wrapper);
    }

    default XxlJobLogReport queryLogReportTotal() {

        List<XxlJobLogReport> xxlJobLogReports = this.selectList(null);

        XxlJobLogReport count =
            xxlJobLogReports.stream()
                .reduce(
                    (x, y) -> {
                        XxlJobLogReport xxlJobLogReport = new XxlJobLogReport();
                        xxlJobLogReport.setRunningCount(x.getRunningCount() + y.getRunningCount());
                        xxlJobLogReport.setSucCount(x.getSucCount() + y.getSucCount());
                        xxlJobLogReport.setFailCount(x.getFailCount() + y.getFailCount());
                        return xxlJobLogReport;
                    })
                .get();
        return count;
    }
}
